package com.atguigu.app.dwd.log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Util.DateFormatUtil;
import com.atguigu.Util.MyKafkaUtil;
import com.google.inject.internal.cglib.core.$LocalVariablesSorter;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.apache.kafka.clients.producer.KafkaProducer;

/**
 * @author hjy
 * @create 2023/3/10 16:33
 */
public class BaseLogApp {
    public static void main(String[] args) throws Exception {
        //todo 1 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
        //设置HDFS用户信息
        //System.setProperty("HADOOP_USER_NAME", "atguigu");
        //todo 2 连接kafka 消费数据
        String topic = "topic_log";
        String groupId="BaseLogApp";
        DataStreamSource<String> logDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //todo 3 过滤数据并转为JsonObj对象
        SingleOutputStreamOperator<JSONObject> jsObjDs = logDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null && !"".equals(value)) {
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(value);
                        out.collect(jsonObject);
                    } catch (JSONException e) {
                        System.out.println("脏数据" + value);
                    }
                }
            }
        });
        //todo 4 keyByMid
        KeyedStream<JSONObject, String> keyedDS = jsObjDs.keyBy(value -> value.getJSONObject("common").getString("mid"));
        //todo 5 新老用户校验
        SingleOutputStreamOperator<JSONObject> jsonObjDsWithNewFlag = keyedDS.map(new RichMapFunction<JSONObject, JSONObject>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last-visit-dt", String.class));
            }

            @Override
            public JSONObject map(JSONObject value) throws Exception {
                String isNew = value.getJSONObject("common").getString("is_new");
                Long ts = value.getLong("ts");
                String dt = DateFormatUtil.toDate(ts);
                /*
                是1
                    判断状态是否为空和状态的值是否等于日期
                        为空或者等于日期，更新状态
                        否则，更新value
                是0
                    判断状态是否为空，为空这更新状态值为"1970-01-01"
                 */
                if ("1".equals(isNew)) {
                    if (valueState.value() == null || dt.equals(valueState.value())) {

                        valueState.update(dt);
                    } else {
                        value.getJSONObject("common").put("is_new", "0");
                    }
                } else {
                    if (valueState.value() == null) {
                        valueState.update("1970-01-01");
                    }
                }
                return value;
            }
        });
        OutputTag<String> startTag = new OutputTag<String>("start") {};
        OutputTag<String> displayTag = new OutputTag<String>("display") {};
        OutputTag<String> actionTag = new OutputTag<String>("action") {};
        OutputTag<String> errorTag = new OutputTag<String>("error") {};
        //todo 6 数据分流
        SingleOutputStreamOperator<String> pageDs = jsonObjDsWithNewFlag.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject value, Context ctx, Collector<String> out) throws Exception {
                JSONObject err = value.getJSONObject("err");
                if (err != null) {
                    ctx.output(errorTag, value.toJSONString());
                    value.remove("err");
                }
                JSONObject start = value.getJSONObject("start");
                if (start != null) {
                    ctx.output(startTag, value.toJSONString());
                } else {
                    //拿到页面id和ts
                    String pageID = value.getJSONObject("page").getString("page_id");
                    Long ts = value.getLong("ts");
                    JSONArray displays = value.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.put("page_id", pageID);
                            display.put("ts", ts);
                            ctx.output(displayTag, display.toJSONString());
                        }
                    }
                    JSONArray actions = value.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.put("page_id", pageID);
                            ctx.output(actionTag, action.toJSONString());
                        }
                    }
                    value.remove("displays");
                    value.remove("actions");
                    out.collect(value.toJSONString());
                }
            }
        });

        //todo 7 获取侧输出流
        DataStream<String> startOutput = pageDs.getSideOutput(startTag);
        DataStream<String> displayOutput = pageDs.getSideOutput(displayTag);
        DataStream<String> actionOutput = pageDs.getSideOutput(actionTag);
        DataStream<String> errOutput = pageDs.getSideOutput(errorTag);
        //todo 8 输出数据
        startOutput.print("startOutput--------->");
        displayOutput.print("displayOutput-------->");
        actionOutput.print("actionOutput-------->");
        errOutput.print("errOutput-------->");
        pageDs.print("pageDs-------->");


        String page_topic = "dwd_traffic_page_log";
        String start_topic = "dwd_traffic_start_log";
        String display_topic = "dwd_traffic_display_log";
        String action_topic = "dwd_traffic_action_log";
        String error_topic = "dwd_traffic_error_log";



        pageDs.addSink(MyKafkaUtil.getKafkaProducer(page_topic));
        startOutput.addSink(MyKafkaUtil.getKafkaProducer(start_topic));
        displayOutput.addSink(MyKafkaUtil.getKafkaProducer(display_topic));
        actionOutput.addSink(MyKafkaUtil.getKafkaProducer(action_topic));
        errOutput.addSink(MyKafkaUtil.getKafkaProducer(error_topic));
        //todo 9 启动任务
        env.execute();
    }
}
